package com.xyz.frame.api.controller;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.xyz.frame.api.cache.NormalCache;
import com.xyz.frame.api.dto.AnswerDto;
import lombok.extern.slf4j.Slf4j;
import org.shzhyun.tts.AliCloudApiOcr;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.ConcurrentMap;

@RestController
@RequestMapping(path = "/ocr")
@Slf4j
public class OcrController {


    @Value("${ocr.filePath}")
    private String ocrFilePath;
    @RequestMapping(method = RequestMethod.POST, path = "/uploadImgToText", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public List<AnswerDto> uploadImgToText(@RequestParam(value = "id",required = false) String id,
                                           @RequestParam(value = "type",required = false) Integer type,
                                           @RequestPart(value = "file") MultipartFile file){
        //
        String path = ocrFilePath+"/"+System.currentTimeMillis()+".png";
        try {
            File fileLocal = FileUtil.writeFromStream(file.getInputStream(), path);
            byte[] fileBytes = fileToByte(fileLocal);
            String imgBase64 = Base64.getEncoder().encodeToString(fileBytes);
            String text = AliCloudApiOcr.sibie("", imgBase64);
            return doScores(text,id);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @RequestMapping(value = "/initAnswer",method = RequestMethod.POST)
    public String  initAnswer(@RequestBody List<AnswerDto> param) {
        log.info("initAnswer request:{}",JSONObject.toJSONString(param));
        NormalCache.setQuestion(param);
        return "success";
    }

    private List<AnswerDto> doScores(String text, String id) {
        List<AnswerDto> result = Lists.newArrayList();
        //解析text  按照题号比对答案
        ConcurrentMap<String, List<AnswerDto>> question = NormalCache.getQuestion();
        result = question.get("试卷1");

//        result.add(
//                AnswerDto.builder()
//                        .answerRight(text)
//                        .build()
//        );

        return result;
    }

    /**
     * 将文件转换为字节数组
     * @param file 文件对象
     * @return 字节数组
     */
    public static byte[] fileToByte(File file) {
        byte[] fileBytes = null;
        try (FileInputStream fis = new FileInputStream(file)) {
            fileBytes = new byte[(int) file.length()];
            fis.read(fileBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileBytes;
    }

    @RequestMapping(value = "/imgRecognition",method = RequestMethod.POST)
    public String  imgRecognition(@RequestBody JSONObject param) {
        log.info("imgRecognition request:{}",JSONObject.toJSONString(param));
        try {
            String text = AliCloudApiOcr.sibie(param.getString("url"), "");
            return text;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
